#!/usr/bin/env python3

import sys, random, json
from common import fget

enc = "UTF-8"
def get_response ():
    settings = json.loads(fget("settings.json"))
    settings["vstring"] = fget("vstring")
    body = fget("main.html.fmt").format(r=random.random(), **settings)
    return settings["content_type"], body.encode(enc)

def main (argv0, argv):
    content_type, body = get_response()
    
    headers = {
        "Content-Type": content_type,
        "Content-Length": str(len(body)),
    }
    headers_str = "".join("{}: {}\r\n".format(k, v) for k, v in headers.items())
    
    response = headers_str.encode(enc) + b"\r\n" + body
    sys.stdout.buffer.write(response)

if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[0], sys.argv[1:]))
    except KeyboardInterrupt:
        pass
